//
//  HomeOnlineTrainDetailViewController.m
//  ZJControlsClass
//
//  Created by wandoufo on 2024/12/8.
//
#import "HomeOnlineTrainModel.h"
#import "HomeOnlineTrainDetailViewController.h"

#import "ZJHomeOnlineDetailWorking.h"
#import "PendChildCollectionViewCell.h"
#import "ZJHomeOnlineCoursewaresTableViewCell.h"
#import "ZJVideoPlayerManager.h"
#import "ZJPDFReaderView.h"
#import "ZJCreateOnlineCourseWorking.h"
#import "ZJHomeOnlineTrainUpdatewaworking.h"
#import "ZJHomeOnlineTrainCoursereTaskwaworking.h"

@interface HomeOnlineTrainDetailViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UITableViewDelegate,UITableViewDataSource,ZJVideoPlayerDelegate,ZJPDFReaderViewDelegate>
@property (nonatomic,strong) ZJHomeOnlineDetailWorking * detailManager;


@property (nonatomic,strong) UICollectionView * tagCollectionView;
@property (nonatomic,strong) NSMutableArray * tagArr;
@property (nonatomic,strong) NSMutableArray * tagSelectArr;
@property (nonatomic,strong) UICollectionView * collectionView;
@property (nonatomic,strong) NSArray * childDataSource;
@property (nonatomic,strong) UIView * playView;
@property (nonatomic,strong) UITableView * coursewaresTableView;
///简介view
@property (nonatomic,strong) UILabel * introductoryLabel;
@property (nonatomic,strong) HomeOnlineCourseModel *courseModel;
@property (nonatomic,strong) HomeOnlineCoursewareModel  *currentModel;
@property (nonatomic,strong) ZJPDFReaderView  *pdfReaderView;

@property (nonatomic, strong) UIView *pdfControlView;
@property (nonatomic, strong) UIButton *previousPageBtn;
@property (nonatomic, strong) UIButton *nextPageBtn;
@property (nonatomic, strong) NSTimer *countdownTimer;
@property (nonatomic, assign) NSInteger countdown;


@property (nonatomic, assign) NSInteger studyDuration;
@property (nonatomic, assign) NSInteger coursewareTotal;

@property (nonatomic, assign) BOOL isCountingDown;

//ZJPDFReaderView
@end

@implementation HomeOnlineTrainDetailViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tagArr = [NSMutableArray arrayWithObjects:@"简介",@"课程", nil];
    self.tagSelectArr = [NSMutableArray arrayWithObjects:@"1",@"0", nil];
    
    [self getCoueseDetali];
    self.view.backgroundColor = [UIColor whiteColor];
    [self configUI];
    
    [ZJVideoPlayerManager shared].delegate = self;
    // Do any additional setup after loading the view.
}
-(void)configUI{
    [self.view addSubview:self.playView];
    [self.view addSubview:self.tagCollectionView];
    [self.view addSubview:self.collectionView];
    
    [self.playView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(StatusBarHeight);
        make.left.right.equalTo(self.view);
        make.height.equalTo(@(ALIGN_HEIGHT_PT(211)));
    }];
    
    [self.tagCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.height.equalTo(@(ALIGN_HEIGHT_PT(45)));
        make.top.equalTo(self.playView.mas_bottom).priority(999);
    }];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.tagCollectionView.mas_bottom);
    }];
    
    [self.view addSubview:self.pdfReaderView];
    [self.pdfReaderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.playView);
    }];
}

-(void)clickeCourseware:(HomeOnlineCoursewareModel *)coursewareModel {
    if (self.currentModel == coursewareModel) {
        return;
    }
    
    if (self.currentModel.status == 1 && self.coursewareTotal > 0){
        [self updateCourseware:self.studyDuration];
    }

    
    self.currentModel = coursewareModel;
    if (self.currentModel.status == 1) {
        [self getCouesereWaraDetali];
    }

    
    // 处理视频和PDF的显示切换
    BOOL isPDF = ![coursewareModel.fileType containsString:@"mp4"];
    self.pdfReaderView.hidden = !isPDF;
    self.pdfControlView.hidden = !isPDF;
    
    // 更新 tagCollectionView 的位置
    [self.tagCollectionView mas_updateConstraints:^(MASConstraintMaker *make) {
        // PDF模式下，tagCollectionView 需要下移 pdfControlView 的高度
        make.top.equalTo(self.playView.mas_bottom).offset(isPDF ? 50 : 0);
    }];
    
    // 添加动画效果
    [UIView animateWithDuration:0.3 animations:^{
        [self.view layoutIfNeeded];
    }];
    
    if (isPDF) {
        // PDF 相关处理
        [[ZJVideoPlayerManager shared] stop];
        self.pdfReaderView.pdfURL = [NSURL URLWithString:coursewareModel.fileUrl];
        self.countdown = 10;
        [self updateNextButtonTitle];
        [self startCountdownTimer];
    } else {
        // 视频相关处理
        [[ZJVideoPlayerManager shared] stop];
        [[ZJVideoPlayerManager shared] playVideoWithUrl:coursewareModel.fileUrl onView:self.playView];
        [[ZJVideoPlayerManager shared] resume];
    }
    
    // 更新UI选中状态
    WeakSelf(self)
    dispatch_async(dispatch_get_main_queue(), ^{
        [weakSelf.courseModel.coursewares enumerateObjectsUsingBlock:^(HomeOnlineCoursewareModel *item, NSUInteger idx, BOOL *stop) {
            item.isSelected = (item == coursewareModel);
        }];
        [weakSelf.coursewaresTableView reloadData];
    });
}


- (void)getCoueseDetali {
    WeakSelf(self)
    [self.detailManager dispatchTaskWithParam:@{@"id":self.taskId,@"courseId":self.model.identifier,@"coursewareId":[self findTargetCourseware:self.model.coursewares].identifier} completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (responseObject && [responseObject[@"code"] intValue] == 200) {
            // 解析返回数据
            weakSelf.courseModel = [HomeOnlineCourseModel mj_objectWithKeyValues:responseObject[@"data"]];
            weakSelf.title =  weakSelf.courseModel.name;
            weakSelf.introductoryLabel.text = weakSelf.courseModel.remarks;
            [weakSelf clickeCourseware:[weakSelf findTargetCourseware:weakSelf.courseModel.coursewares]];
        }
        [self.coursewaresTableView.mj_header endRefreshing];
    }];
}

- (void)getCouesereWaraDetali {
    [[ZJHomeOnlineTrainCoursereTaskwaworking new] dispatchTaskWithParam:@{@"coursewareId" : self.currentModel.identifier ,@"id":self.taskId} completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (responseObject && [responseObject[@"code"] intValue] == 200) {
            if ([responseObject[@"code"] intValue] >0 ) {
                self.studyDuration = [responseObject[@"code"] intValue];
                if ([self.currentModel.fileType isEqualToString:@"mp4"]) {
                    [[ZJVideoPlayerManager shared] seekToTime:(NSTimeInterval)self.studyDuration];
                } else {
                    [self.pdfReaderView goToPage:self.studyDuration -1 animated:false];
                }
            }
        }
    }];
}

// ... 添加计时器和按相关方法 ...
- (void)startCountdownTimer {
    self.isCountingDown = YES;
    [self updateNextButtonStyle];
    [self.countdownTimer invalidate];
    self.countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats:YES];
}

- (void)updateCountdown {
    if (self.countdown > 0) {
        self.countdown--;
        [self updateNextButtonTitle];
    } else {
        [self.countdownTimer invalidate];
        self.isCountingDown = NO;
        [self updateNextButtonStyle];
    }
}

- (void)updateNextButtonTitle {
    [self.nextPageBtn setTitle:[NSString stringWithFormat:@"下一页(%lds)", (long)self.countdown] forState:UIControlStateNormal];
}

- (void)previousPageAction {
    NSLog(@"点击上一页");
    if (self.pdfReaderView) {
        [self.pdfReaderView goToPreviousPage:YES];
    }
    
}

- (void)nextPageAction {
    NSLog(@"点击下一页");
    if (self.countdown == 0 && self.isCountingDown == false) {
        if (self.pdfReaderView) {
            [self.pdfReaderView goToNextPage:YES];
            self.countdown = 10;
            [self updateNextButtonTitle];
            [self startCountdownTimer];
        }
    } else {
        NSLog(@"倒计时未结束，还剩 %ld 秒", (long)self.countdown);
    }
}


//创建课件学习任务
-(void)createCourseware:(NSInteger)total {
    if (self.currentModel.status == 0) {
        [[ZJCreateOnlineCourseWorking new] dispatchTaskWithParam:@{@"taskId":self.taskId,@"courseId":self.model.identifier,@"coursewareId":self.currentModel.identifier,@"total":@(total)} completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
            if (responseObject && [responseObject[@"code"] intValue] == 200) {
                self.currentModel.status= 1;
            }
        }];
    }
}

//更新课件学习任务
-(void)updateCourseware:(NSInteger)studyDuration {
    [[ZJHomeOnlineTrainUpdatewaworking new] dispatchTaskWithParam:@{@"taskId":self.taskId,@"courseId":self.model.identifier,@"coursewareId":self.currentModel.identifier,@"status":@(self.currentModel.status),@"progress":@(studyDuration)} completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (responseObject && [responseObject[@"code"] intValue] == 200) {
            if (self.currentModel.status == 0) {
                self.currentModel.status = 1;
            } else if (self.currentModel.status == 1) {
                self.currentModel.status = 2;
            } else {
                self.currentModel.status = 3;
            }
        }
    }];
}

#pragma mark -- ZJPDFReaderViewDelegate
- (void)pdfReaderDidUpdateCurrentPage:(NSInteger)currentPage totalPages:(NSInteger)totalPages  {
//    if (currentPage != self.studyDuration) {
        self.studyDuration = currentPage + 1;
        self.coursewareTotal = totalPages;
        if (self.currentModel.status != 0) {
            if (self.currentModel.status == 1 && self.studyDuration == totalPages) {
                self.currentModel.status = 2;
            }
        }
        if (self.currentModel.status == 0) {
            [self createCourseware:self.coursewareTotal];
        } else {
            [self updateCourseware:self.studyDuration];
        }
//        [self createCourseware:self.studyDuration];
//    }
}

#pragma mark -- ZJVideoPlayerDelegate
- (void)videoPlayer:(id)player currentTime:(NSTimeInterval)currentTime totalTime:(NSTimeInterval)totalTime {
    self.studyDuration = (NSInteger)currentTime;
    self.coursewareTotal = (NSInteger)totalTime;
    if (self.studyDuration == self.coursewareTotal && self.currentModel.status < 2) {
        self.currentModel.status = 2;
        [self updateCourseware:self.studyDuration];
    }
}

- (void)onlyOnceVideoPlayer:(id)player totalTime:(NSTimeInterval)totalTime  {
    NSInteger intTotalTime = (NSInteger)totalTime;
    [self createCourseware:intTotalTime];
//    NSLog(@"onlyOnceVideoPlayer    %ld   ",(long)intTotalTime);
}



#pragma mark -- protocolClickButtonChangeCollectionViewContentOffsetDelegate
-(void)ClickButtonWithIndex:(NSInteger)index{
    CGFloat offsetX = index * SCREEN_WIDTH;
    [self.collectionView setContentOffset:CGPointMake(offsetX, 0)];
    
    [self.tagSelectArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [self.tagSelectArr replaceObjectAtIndex:idx withObject:@"0"];
    }];
    [self.tagSelectArr replaceObjectAtIndex:index withObject:@"1"];
    [self.tagCollectionView reloadData];
    
}


#pragma mark -- UITableViewDelegate,UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
  
    return self.courseModel.coursewares.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZJHomeOnlineCoursewaresTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ZJHomeOnlineCoursewaresTableViewCell"];
    if (!cell){
        cell = [[ZJHomeOnlineCoursewaresTableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"ZJHomeOnlineCoursewaresTableViewCell"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
//    HomeOnlineCoursewareModel *model = self.courseModel.coursewares[indexPath.row];
    cell.model = self.courseModel.coursewares[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    [self clickeCourseware:self.courseModel.coursewares[indexPath.row]];
}


// 添加section header高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return  0.001;
}

#pragma mark -- UICollectionViewDelegate,UICollectionViewDataSource
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if ([collectionView isEqual:self.tagCollectionView]) {
        return self.tagArr.count;
    }
    return self.childDataSource.count;
}


-(__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if ([collectionView isEqual:self.tagCollectionView]) {
        PendChildCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PendChildCollectionViewCell" forIndexPath:indexPath];
        
        if ([self.tagSelectArr[indexPath.row] isEqualToString:@"1"]) {
            cell.follewView.backgroundColor = COLOR_RGB(50, 113, 237);
            cell.label.textColor = COLOR_RGB(50, 113, 237);
        }else{
            cell.follewView.backgroundColor = [UIColor clearColor];
            cell.label.textColor = COLOR_RGB(102, 102, 102);
        }
        cell.label.text = [NSString stringWithFormat:@"%@",self.tagArr[indexPath.row]];
        
        return cell;
    }else{
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([UICollectionViewCell class]) forIndexPath:indexPath];
        UIView *childView = self.childDataSource[indexPath.row];
            [cell.contentView addSubview:childView];
            [childView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.bottom.top.equalTo(cell.contentView);
            }];
        
        if (indexPath.row == 0) {
            [self.introductoryLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.top.equalTo(childView).offset(12);
                make.right.equalTo(childView).offset(-12);
            }];
        }else {
            [self.coursewaresTableView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.top.equalTo(childView);
                make.right.bottom.equalTo(childView).offset(-12);
            }];
        }
        return cell;
    }
    return nil;
}



-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if ([collectionView isEqual:self.tagCollectionView]) {
        
        [self collectionViewClickIndex:indexPath.row];
    
    }
}

-(void)collectionViewClickIndex:(NSUInteger ) index {
    CGFloat offsetX = index* SCREEN_WIDTH;
    [self.collectionView setContentOffset:CGPointMake(offsetX, 0)];
    
    
    [self.tagSelectArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [self.tagSelectArr replaceObjectAtIndex:idx withObject:@"0"];
    }];
    [self.tagSelectArr replaceObjectAtIndex:index withObject:@"1"];
    NSLog(@"collectionViewClickIndex   %ld",index);
    [self.tagCollectionView reloadData];
}



#pragma mark - item宽高
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([collectionView isEqual: self.tagCollectionView]) {
        return CGSizeMake(60, ALIGN_HEIGHT_PT(45));
    }else{
        return self.collectionView.bounds.size;
    }
}

#pragma mark - <UICollectionViewDelegateFlowLayout>
#pragma mark - Y间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return  ALIGN_WIDTH_PT(0);
}
#pragma mark - X间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return  ALIGN_WIDTH_PT(0);
}


#pragma mark -- 懒加载

-(UICollectionView *)tagCollectionView{
    if (!_tagCollectionView) {
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _tagCollectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
        _tagCollectionView.delegate = self;
        _tagCollectionView.dataSource = self;
        _tagCollectionView.userInteractionEnabled = YES;
        _tagCollectionView.backgroundColor = [UIColor clearColor];
        _tagCollectionView.showsVerticalScrollIndicator = false;
        _tagCollectionView.showsHorizontalScrollIndicator = false;
        
        // cell
        [_tagCollectionView registerClass:[PendChildCollectionViewCell class] forCellWithReuseIdentifier:@"PendChildCollectionViewCell"];
    }
    return _tagCollectionView;
}



- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new];
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.bounces = NO;
        _collectionView.pagingEnabled = YES;
        _collectionView.scrollEnabled = NO;
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([UICollectionViewCell class])];
        _collectionView.backgroundColor = [UIColor clearColor];
    }
    return _collectionView;
}

- (NSArray *)childDataSource{
    if (!_childDataSource) {
//        HomeOnlineTrainListViewController * oneVc =[HomeOnlineTrainListViewController new];
//        oneVc.trainStatus = 0;
//        
//        HomeOnlineTrainListViewController * twoVc =[HomeOnlineTrainListViewController new];
//        twoVc.trainStatus = 1;
//        
//        HomeOnlineTrainListViewController * threeVc =[HomeOnlineTrainListViewController new];
//        threeVc.trainStatus = 2;
//        
//        [self addChildViewController:oneVc];
//        
//        [self addChildViewController:twoVc];
//        
//        [self addChildViewController:threeVc];
        UIView *oneView = [UIView new];
        oneView.backgroundColor = [UIColor whiteColor];
        [oneView addSubview:self.introductoryLabel];
        
        
        UIView *twoView = [UIView new];
        twoView.backgroundColor = [UIColor whiteColor];
        [twoView addSubview:self.coursewaresTableView];
        
        _childDataSource = @[oneView, twoView];
        
    }
    return _childDataSource;
}
// 添加��方法来查找目标courseware
- (HomeOnlineCoursewareModel *)findTargetCourseware:(NSArray *)cours{
    // 查找状态为1或2的第一条数据
    for (HomeOnlineCoursewareModel *courseware in cours) {
        if (courseware.status == 1 || courseware.status == 0) {
            return courseware;
        }
    }
    if (cours.count == 0) {
        HomeOnlineCoursewareModel *coursewareModel = [HomeOnlineCoursewareModel new];
        coursewareModel.identifier = @"";
        return  coursewareModel;
    }
    // 如果没有找到状态为1或2的数据，返回最后一条数据
    return cours.lastObject;
}
- (UIView *)playView {
    if (!_playView) {
        _playView = [[UIView alloc] init];
        _playView.backgroundColor = [UIColor blueColor];
        
    }
    return  _playView;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (ZJHomeOnlineDetailWorking *)detailManager{
    if (!_detailManager) {
        _detailManager = [[ZJHomeOnlineDetailWorking alloc] init];
        
    }
    return _detailManager;
}

- (UILabel *)introductoryLabel {
    if (!_introductoryLabel) {
        _introductoryLabel = [[UILabel alloc] init];
        _introductoryLabel.font = [UIFont systemFontOfSize:14];
        _introductoryLabel.numberOfLines = 0;
//        _introductoryLabel.textAlignment = NSTextAlignment
        _introductoryLabel.textColor = [UIColor colorWithHexString:@"181818"];
    }
    return _introductoryLabel;
}

- (ZJPDFReaderView *)pdfReaderView {
    if (!_pdfReaderView) {
        _pdfReaderView = [[ZJPDFReaderView alloc] init];
        _pdfReaderView.hidden = YES; // 默认隐藏
        _pdfReaderView.delegate = self;
    }
    return _pdfReaderView;
}

-(UITableView *)coursewaresTableView{
    if (!_coursewaresTableView){
        _coursewaresTableView = [[UITableView alloc]initWithFrame:CGRectZero style:(UITableViewStylePlain)];
        _coursewaresTableView.delegate = self;
        _coursewaresTableView.dataSource = self;
        _coursewaresTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _coursewaresTableView.backgroundColor = [UIColor whiteColor];
        _coursewaresTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//            pageNo = 1;
//            [self.TableViewParamer addEntriesFromDictionary:@{@"pageNo":@(pageNo)}];
            [self getCoueseDetali];
        }];
    }
    return _coursewaresTableView;
}

- (UIView *)pdfControlView {
    if (!_pdfControlView) {
        _pdfControlView = [[UIView alloc] init];
        _pdfControlView.backgroundColor = [UIColor whiteColor];
        _pdfControlView.hidden = YES;
        _pdfControlView.userInteractionEnabled = YES;
        
        [self.view addSubview:_pdfControlView];
        [_pdfControlView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.playView);
            make.top.equalTo(self.playView.mas_bottom);
            make.height.equalTo(@50);
        }];
        
        [_pdfControlView addSubview:self.previousPageBtn];
        [_pdfControlView addSubview:self.nextPageBtn];
        
        [self.previousPageBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(_pdfControlView.mas_centerX).offset(-15);
            make.centerY.equalTo(_pdfControlView);
            make.width.equalTo(@80);
            make.height.equalTo(@30);
        }];
        
        [self.nextPageBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_pdfControlView.mas_centerX).offset(15);
            make.centerY.equalTo(_pdfControlView);
            make.width.equalTo(@80);
            make.height.equalTo(@30);
        }];
    }
    return _pdfControlView;
}

- (UIButton *)previousPageBtn {
    if (!_previousPageBtn) {
        _previousPageBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_previousPageBtn setTitle:@"上一页" forState:UIControlStateNormal];
        [_previousPageBtn setTitleColor:COLOR_RGB(50, 113, 237) forState:UIControlStateNormal];
        [_previousPageBtn.titleLabel setFont:[UIFont systemFontOfSize:13]];
        
        // 设置边框
        _previousPageBtn.layer.borderWidth = 1.0;
        _previousPageBtn.layer.borderColor = COLOR_RGB(50, 113, 237).CGColor;
        _previousPageBtn.layer.cornerRadius = 15;
        _previousPageBtn.backgroundColor = [UIColor whiteColor];
        
        // 确保事件绑定正确
        [_previousPageBtn addTarget:self 
                           action:@selector(previousPageAction) 
                 forControlEvents:UIControlEventTouchUpInside];
        
        // 确保按钮可以交互
        _previousPageBtn.userInteractionEnabled = YES;
    }
    return _previousPageBtn;
}

- (UIButton *)nextPageBtn {
    if (!_nextPageBtn) {
        _nextPageBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_nextPageBtn setTitleColor:COLOR_RGB(50, 113, 237) forState:UIControlStateNormal];
        [_nextPageBtn.titleLabel setFont:[UIFont systemFontOfSize:13]];
        
        // 设置边框
        _nextPageBtn.layer.borderWidth = 1.0;
        _nextPageBtn.layer.borderColor = COLOR_RGB(50, 113, 237).CGColor;
        _nextPageBtn.layer.cornerRadius = 15;
        _nextPageBtn.backgroundColor = [UIColor whiteColor];
        
        // 确保事件绑定正确
        [_nextPageBtn addTarget:self 
                       action:@selector(nextPageAction) 
             forControlEvents:UIControlEventTouchUpInside];
        
        // 确保按钮可以交互
        _nextPageBtn.userInteractionEnabled = YES;
    }
    return _nextPageBtn;
}

- (void)deallocData {
    [self updateCourseware:self.studyDuration];
    [[ZJVideoPlayerManager shared] destroyPlayer];
    [self.countdownTimer invalidate];
    self.countdownTimer = nil;
}


- (void)dealloc
{
    NSLog(@"HomeOnlineTrainDetailViewController   dealloc");
}

- (void)viewDidDisappear:(BOOL)animated {
    [self deallocData];
    [super viewDidDisappear:animated];
    
}

- (void)updateNextButtonStyle {
    if (self.isCountingDown) {
        self.nextPageBtn.enabled = NO;
        [self.nextPageBtn setTitleColor:[COLOR_RGB(50, 113, 237) colorWithAlphaComponent:0.5] forState:UIControlStateNormal];
        self.nextPageBtn.layer.borderColor = [COLOR_RGB(50, 113, 237) colorWithAlphaComponent:0.5].CGColor;
    } else {
        self.nextPageBtn.enabled = YES;
        [self.nextPageBtn setTitleColor:COLOR_RGB(50, 113, 237) forState:UIControlStateNormal];
        self.nextPageBtn.layer.borderColor = COLOR_RGB(50, 113, 237).CGColor;
    }
}

@end
